package com.klun.concDesign;

public class GoodSuspend {

    public static Object u = new Object();

    // 静态内部类
    public static class ChangeObjectThread extends Thread{

        // 此处为什么要用 volatile 关键字 没用 static ？
        volatile boolean suspendme = false;

        //挂起
        public void suspendMe(){
            suspendme =true;
        }
        // 继续执行
        public void resumeMe(){
            suspendme =false;
            synchronized (this){
                notify();
            }
        }

        @Override
        public void run() {
            //
            while (true){
                synchronized (this){ //this = GoodSuspend
                    while (suspendme){
                        try{
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                synchronized (u){ // 新建的 Object 加锁
                    System.out.println("in ChangeObjectThread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Thread.yield(); // 礼让
            }
        }
    }
    public static class ReadObjectThread extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized (u){
                    System.out.println("in ReadObjectThread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ChangeObjectThread t1 = new ChangeObjectThread();
        ReadObjectThread t2 = new ReadObjectThread();
        t1.start();
        t2.start();
        Thread.sleep(1000);
        t1.suspendMe();
        System.out.println("t1 等待 2S");
        Thread.sleep(20000);
        System.out.println("继续 t1");
        t1.resumeMe();
    }

}
